<template>
  <div class="account-list-component">
    <!-- 表格模式 -->
    <a-table
      v-if="mode === 'table'"
      :columns="columns"
      :data-source="accounts"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      bordered
      :class="'custom-table'"
      :scroll="{ x: 'max-content' }"
    >
      <template #image="{ text }">
        <img :src="filterImage(text)" alt="图片" style="width: 30px; height: 30px; object-fit: cover; border-radius: 8px;" />
      </template>
      <template #updatedAt="{ text }">
        {{ formatDate(text) }}
      </template>
      <template #server="{ text }">
        <a-tag :color="text === 'QQ' ? 'blue' : 'green'">{{ text }}</a-tag>
      </template>
      <template #loginMethod="{ text }">
        <a-tag :color="text === '扫码登录' ? 'orange' : 'purple'">{{ text }}</a-tag>
      </template>
      <template #rank="{ text }">
        <a-tag :color="getRankColor(text)">{{ text }}</a-tag>
      </template>
      <template #safetyBox="{ text }">
        <a-tag :color="getSafetyBoxColor(text)">{{ text }}</a-tag>
      </template>
      <template #totalAssets="{ text }">
        {{ formatAssets(text) }}
      </template>
      <template #coinAssets="{ text }">
        {{ formatAssets(text) }}
      </template>
      <template #ratio="{ text }">
        {{ formatRatio(text) }}
      </template>
      <template #status="{ text }">
        <a-tag :color="getStatusColor(text)">{{ getStatusText(text) }}</a-tag>
      </template>
      <template #actions="{ record }">
        <div class="action-buttons">
          <a-button size="small" type="primary" @click="handleDetail(record)">详情</a-button>
          <!-- <a-button size="small" type="primary" @click="handleDetail(record)">详情</a-button>
          <a-button v-if="showEdit && canEdit(record)" size="small" @click="handleEdit(record)">编辑</a-button>
          <a-popconfirm
            v-if="showDelete && canDelete(record)"
            title="确定要删除这个账号吗？"
            @confirm="handleDelete(record)"
          >
            <a-button size="small" danger>删除</a-button>
          </a-popconfirm> -->
        </div>
      </template>
    </a-table>

    <!-- 卡片模式 -->
    <div v-else-if="mode === 'card'" class="account-cards">
      <a-spin :spinning="loading">
        <div v-if="accounts.length > 0" class="cards-container">
          <a-card
            v-for="account in accounts"
            :key="account._id"
            size="small"
            class="account-card"
          >
            <div class="account-item">
              <div class="account-info">
                <strong>{{ account.number }}</strong>
                <a-tag :color="getStatusColor(account.status)">{{ getStatusText(account.status) }}</a-tag>
                <div class="account-details">
                  <span>{{ account.server }} | {{ account.rank }}</span>
                  <span>纯币: {{ formatAssets(account.coinAssets) }}</span>
                  <span>价格: ¥{{ account.price }}</span>
                </div>
              </div>
              <div class="account-actions">
                <a-button size="small" @click="handleView(account)">查看</a-button>
                <a-button size="small" type="primary" @click="handleDetail(account)">详情</a-button>
                <a-button v-if="showEdit && canEdit(account)" size="small" @click="handleEdit(account)">编辑</a-button>
                <a-popconfirm
                  v-if="showDelete && canDelete(account)"
                  title="确定要删除这个账号吗？"
                  @confirm="handleDelete(account)"
                >
                  <a-button size="small" danger>删除</a-button>
                </a-popconfirm>
              </div>
            </div>
          </a-card>
        </div>
        
        <div v-else class="empty-state">
          <a-empty :description="emptyText">
            <slot name="empty-action">
              <a-button type="primary" @click="$emit('create')">
                立即发布
              </a-button>
            </slot>
          </a-empty>
        </div>
      </a-spin>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import accountAPI from '~/api/account'

// Props
const props = defineProps({
  // 数据源
  data: {
    type: Array,
    default: () => []
  },
  // 显示模式：table | card
  mode: {
    type: String,
    default: 'table'
  },
  // 是否显示编辑按钮
  showEdit: {
    type: Boolean,
    default: false
  },
  // 是否显示删除按钮
  showDelete: {
    type: Boolean,
    default: false
  },
  // 是否显示分页
  showPagination: {
    type: Boolean,
    default: true
  },
  // 分页配置
  paginationConfig: {
    type: Object,
    default: () => ({
      current: 1,
      pageSize: 10,
      total: 0,
      showTotal: total => `共 ${total} 条`
    })
  },
  // 空状态文本
  emptyText: {
    type: String,
    default: '暂无数据'
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  },
  // 当前用户信息（用于权限判断）
  currentUser: {
    type: Object,
    default: null
  }
})

// Emits
const emit = defineEmits([
  'view',
  'detail',
  'edit',
  'delete',
  'create',
  'table-change',
  'refresh'
])

// 响应式数据
const accounts = ref(props.data)
const pagination = ref(props.paginationConfig)

// 监听数据变化
watch(() => props.data, (newData) => {
  accounts.value = newData
}, { deep: true })

watch(() => props.paginationConfig, (newConfig) => {
  pagination.value = newConfig
}, { deep: true })

// 表格列定义
const columns = computed(() => {
  const baseColumns = [
    { title: '编号', dataIndex: 'number', key: 'number', width: 100, fixed: 'left' },
    { title: '区服', dataIndex: 'server', key: 'server', width: 80, slots: { customRender: 'server' } },
    { title: '账密', dataIndex: 'loginMethod', key: 'loginMethod', slots: { customRender: 'loginMethod' }, ellipsis: true },
    { title: '段位', dataIndex: 'rank', key: 'rank', slots: { customRender: 'rank' }, ellipsis: true },
    { title: '总资仓(m)', dataIndex: 'totalAssets', key: 'totalAssets', slots: { customRender: 'totalAssets' }, ellipsis: true, sorter: true },
    { title: '纯币资产(m)', dataIndex: 'coinAssets', key: 'coinAssets', slots: { customRender: 'coinAssets' }, ellipsis: true, sorter: true },
    { title: '比例', dataIndex: 'ratio', key: 'ratio', ellipsis: true, sorter: true, slots: { customRender: 'ratio' } },
    { title: '等级', dataIndex: 'level', key: 'level', ellipsis: true },
    { title: '体力等级', dataIndex: 'energyLevel', key: 'energyLevel', ellipsis: true },
    { title: '安全箱', dataIndex: 'safetyBox', key: 'safetyBox', slots: { customRender: 'safetyBox' }, ellipsis: true },
    { title: 'awm子弹', dataIndex: 'awmBullets', key: 'awmBullets', ellipsis: true },
    { title: '价格(元)', dataIndex: 'price', key: 'price', ellipsis: true, sorter: true },
    { title: '押金(元)', dataIndex: 'deposit', key: 'deposit', ellipsis: true },
    { title: '图片', dataIndex: 'image', key: 'image', slots: { customRender: 'image' }, ellipsis: true },
    { title: '收号时间', dataIndex: 'updatedAt', key: 'updatedAt', slots: { customRender: 'updatedAt' }, ellipsis: true },
    { title: '备注', dataIndex: 'remark', key: 'remark', ellipsis: true },
    { title: '操作', key: 'actions', fixed: 'right', slots: { customRender: 'actions' } }
  ]

  // 如果显示状态列
  if (props.showStatus) {
    baseColumns.splice(1, 0, { title: '状态', dataIndex: 'status', key: 'status', width: 100, slots: { customRender: 'status' } })
  }

  // 如果显示操作列
  if (props.showEdit || props.showDelete) {
    baseColumns.push({ title: '操作', key: 'actions', width: 150, fixed: 'right', slots: { customRender: 'actions' } })
  }

  return baseColumns
})

// 格式化函数
const formatDate = (ts) => {
  if (!ts) return ''
  const d = new Date(ts)
  return d.toLocaleDateString() + ' ' + d.toLocaleTimeString()
}

const formatAssets = (value) => {
  if (!value) return '0m'
  return (value / 1000000).toFixed(1) + 'm'
}

const formatRatio = (value) => {
  if (!value) return '1:1'
  return `1:${value}`
}

const getRankColor = (rank) => {
  const colorMap = {
    '无段位': 'default',
    '青铜': 'brown',
    '白银': 'silver',
    '黄金': 'gold',
    '铂金': 'cyan',
    '钻石': 'blue',
    '黑鹰': 'purple',
    '三角洲巅峰': 'red'
  }
  return colorMap[rank] || 'default'
}

const getSafetyBoxColor = (safetyBox) => {
  const colorMap = {
    '顶级安全箱 (3x3)': 'red',
    '高级安全箱 (2x3)': 'orange',
    '进阶安全箱 (2x2)': 'blue',
    '基础安全箱 (1x2)': 'green'
  }
  return colorMap[safetyBox] || 'default'
}

const getStatusColor = (status) => {
  const colorMap = {
    '待审核': 'orange',
    '已上架': 'green',
    '已下架': 'default',
    '已出租': 'blue',
    '已消耗': 'red',
    '审核失败': 'red'
  }
  return colorMap[status] || 'default'
}

const getStatusText = (status) => {
  const textMap = {
    '待审核': '待审核',
    '已上架': '已上架',
    '已下架': '已下架',
    '已出租': '已出租',
    '已消耗': '已消耗',
    '审核失败': '审核失败'
  }
  return textMap[status] || status
}

const filterImage = (item) => {
    if (typeof item === 'string') {
      try {
        const arr = JSON.parse(item);
        return Array.isArray(arr) && arr.length > 0 ? arr[0] : '';
      } catch (e) {
        return '';
      }
    }
    return Array.isArray(item) && item.length > 0 ? item[0] : '';
}

// 权限判断
const canEdit = (account) => {
  if (!props.currentUser) return false
  return account.owner === props.currentUser.id || props.currentUser.role === 'admin'
}

const canDelete = (account) => {
  if (!props.currentUser) return false
  if (account.status === '已出租') return false
  return account.owner === props.currentUser.id || props.currentUser.role === 'admin'
}

// 事件处理
const handleTableChange = (pagination, filters, sorter) => {
  emit('table-change', { pagination, filters, sorter })
}

const handleView = async (account) => {
  const accountId = account._id;
  const accountData = await accountAPI.getAccount(accountId);
  console.log(accountData);
  // emit('view', account)
}

const handleDetail = (account) => {
  // 跳转到账号详情页
  navigateTo(`/accounts/${account._id}`)
}

const handleEdit = (account) => {
  emit('edit', account)
}

const handleDelete = (account) => {
  emit('delete', account)
}
</script>

<style scoped>
.account-list-component {
  width: 100%;
}

.custom-table :deep(.ant-table-thead > tr > th) {
  background-color: #000 !important;
  color: #fff !important;
  font-size: 12px !important;
  white-space: nowrap !important;
  font-weight: 500 !important;
}

.custom-table :deep(.ant-table-thead > tr > th .ant-table-column-title) {
  color: #fff !important;
}

.custom-table :deep(.ant-table-tbody > tr > td) {
  font-size: 12px !important;
}

.action-buttons {
  display: flex;
  gap: 4px;
}

.account-cards {
  width: 100%;
}

.cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.account-card {
  transition: all 0.3s ease;
}

.account-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.account-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.account-info {
  flex: 1;
}

.account-info strong {
  display: block;
  margin-bottom: 4px;
  font-size: 14px;
}

.account-details {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
}

.account-details span {
  display: block;
  margin-bottom: 2px;
}

.account-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}
</style> 